#! /usr/bin/env python
import os
import sys
import logging
import optparse
import sipconfig

def create_options_parser():
    """Create a parser to extract value from command line options."""
    parser = optparse.OptionParser( usage = "python %prog [opts]" )
    parser.add_option( "-t", "--otdir",
                       action = "store",
                       type   = "string",
                       help   = "Path to libserial C++ library installation" )
    return parser

def main():
    #
    # Parse the command line options specified by the user.
    #
    parser = create_options_parser()
    (options, arguments) = parser.parse_args()
    #
    # The name of the build file generated by SIP and used by the
    # build system.
    #
    build_file = "libserial.sbf"
    logging.info( "Build file is " + build_file )
    #
    # Get the configuration information for the local SIP installation.
    #
    logging.info( "Reading sip configuration." ) 
    config = sipconfig.Configuration()
    config.qt_framework = None
    #
    # Construct and run SIP to generate the module's C++ code.
    #
    sip_command = " ".join( [ config.sip_bin,
                              "-c", ".",
                              "-e",
                              "-b", build_file,
                              "libserial.sip" ] )
    logging.info( "Running sip command: '" + sip_command + "'" )
    os.system( sip_command )
    #
    # Create the Makefile with threading support as the libserial libraries
    # use threads implicitly.
    #
    makefile = sipconfig.SIPModuleMakefile( config,
                                            build_file=build_file,
                                            threaded=1,
                                            makefile="Makefile.sip" )
    #
    # Add the library we are wrapping.  The name doesn't include any platform
    # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
    # ".dll" extension on Windows).
    #
    makefile.extra_include_dirs = [ "../src" ]
    makefile.extra_lib_dirs     = [ "../src/.libs" ]
    makefile.extra_libs         = [ "serial" ]
    #
    # Generate the Makefile itself.
    #
    makefile.generate()
###############################################################################
# The script starts here.
###############################################################################

if __name__ == "__main__":
    try:
        logging.basicConfig( level  = logging.DEBUG,
                             format = '%(asctime)s %(levelname)s %(message)s' )
        main()
    except SystemExit:
        raise
    except:
        print \
"""An internal error occured.  Please report all the output from the program,
including the following traceback.
"""
        raise
